﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Security;
using Capstone.Infrastructure.Data.Services;
using Capstone.Services.ShouldntBeHere;

namespace Capstone.Application.Web.Home.Projects.Sprints {
    public partial class Sprint : System.Web.UI.Page 
    {
        public List<Infrastructure.Data.EF.Entities.Sprint> Sprints
        {
            get { return Session["Sprints"] as List<Infrastructure.Data.EF.Entities.Sprint> ?? new List<Infrastructure.Data.EF.Entities.Sprint>(); }
            set { Session["Sprints"] = value; }
        } 

        public List<Infrastructure.Data.EF.Entities.ReleaseBacklog> ReleaseBacklogs
        {
            get
            {
                return Session["ReleaseBackLogs"] as List<Infrastructure.Data.EF.Entities.ReleaseBacklog> ??
                       new List<Infrastructure.Data.EF.Entities.ReleaseBacklog>();
            }
            set { Session["ReleaseBackLogs"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Request.IsAuthenticated)
            {
                FormsAuthentication.RedirectToLoginPage();
            }
            
            if (!IsPostBack)
            {
                BindReleaseDropDown();
                BindGrid(1);
            }
        }

        protected void ddlReleaseBacklog_Changed(object sender, EventArgs e)
        {
            int value;
            if (int.TryParse(ddlReleaseBacklog.SelectedValue, out value))
                BindGrid(value);
        }

        private void BindReleaseDropDown()
        {
            var service = new ApplicationServiceBase();
            var request = new GetReleaseBacklogRequest {BacklogID = 1};
            var response = service.GetReleaseBacklog(request);
            if (response.IsSuccess)
            {
                ReleaseBacklogs = response.Result;
            }
            ddlReleaseBacklog.DataSource = ReleaseBacklogs;
            ddlReleaseBacklog.DataTextField = "Name";
            ddlReleaseBacklog.DataValueField = "ID";
            ddlReleaseBacklog.DataBind();
        }

        private void BindGrid(int backlogid)
        {
            var service = new ApplicationServiceBase();
            var request = new GetSprintsRequest { ReleaseBacklogID = backlogid };
            var response = service.GetSprints(request);
            if (response.IsSuccess)
            {
                Sprints = response.Result;
            }
            gvSprints.DataSource = Sprints;
            gvSprints.DataBind();
        }
    }
}